package 二级缓存;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/8/15 16:44
 * @description:
 * @version:
 */
public class FirstLevelCache implements Cache{
    private Map<String, CacheItem> cacheMap = new HashMap<>();
    private int maxCapacity;

    public FirstLevelCache(int maxCapacity) {
        this.maxCapacity = maxCapacity;
    }

    @Override
    public Object get(String key) {
        CacheItem item = cacheMap.get(key);
        if (item != null && !item.isExpired()) {
            return item.getValue();
        }
        return null;
    }

    @Override
    public void put(String key, Object value, long expirationTime) {
        if (cacheMap.size() >= maxCapacity) {
            removeExpired();
        }
        cacheMap.put(key, new CacheItem(value, expirationTime));
    }

    @Override
    public void remove(String key) {
        cacheMap.remove(key);
    }

    @Override
    public void clear() {
        cacheMap.clear();
    }

    @Override
    public void removeExpired() {
        Iterator<Map.Entry<String, CacheItem>> iterator = cacheMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, CacheItem> entry = iterator.next();
            if (entry.getValue().isExpired()) {
                iterator.remove();
            }
        }
    }
}
